#include "ConnectItemModel.h"
#include <QColor>

ConnectItemModel::ConnectItemModel(QObject *parent) :
	QAbstractItemModel (parent)
{
}

void ConnectItemModel::reloadData(QList<PortConnectInfo> ports)
{
	_ports = ports;
	emit layoutAboutToBeChanged();
	emit layoutChanged();
}

QVariant ConnectItemModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	QVariant result;

	if (orientation == Qt::Horizontal
			&& role == Qt::DisplayRole)
	{
		switch (section)
		{
		case SECTION_PORT:
			result = tr("Port"); break;
		case SECTION_AVAILABLE:
			result = tr("Availability"); break;
		case SECTION_STATUS:
			result = tr("Connection"); break;
		}
	}

	return result;
}

QVariant ConnectItemModel::data(const QModelIndex &index, int role) const
{
	QVariant result;
	if (index.isValid())
	{
		if(role == Qt::DisplayRole)
		{
			switch(index.column())
			{
			case SECTION_PORT:
				result = _ports.at(index.row()).name;
				break;
			case SECTION_AVAILABLE:
				result = _ports.at(index.row()).available ? tr("free") : tr("busy");
				break;
			case SECTION_STATUS:
				result = _ports.at(index.row()).connection.isEmpty() ? tr("no") : tr("yes (") + _ports.at(index.row()).connection + ")";
				break;
			default:
				break;
			}
		}

		else if(role == Qt::TextColorRole)
		{
			switch(index.column())
			{
			case SECTION_PORT:
				result = QColor(Qt::black);
				break;
			case SECTION_AVAILABLE:
				result = _ports.at(index.row()).available ? QColor(Qt::green) : QColor(Qt::red);
				break;
			case SECTION_STATUS:
				result = _ports.at(index.row()).connection.isEmpty() ? QColor(Qt::red) : QColor(Qt::green);
				break;
			default:
				break;
			}
		}
	}
	return result;
}

QModelIndex ConnectItemModel::index(int row, int column, const QModelIndex &parent) const
{
	return parent.isValid()? QModelIndex() : createIndex(row, column);
}

QModelIndex ConnectItemModel::parent(const QModelIndex &index) const
{
	Q_UNUSED(index);
	return QModelIndex();
}

int ConnectItemModel::rowCount(const QModelIndex &parent) const
{
	return parent.isValid() ? 0 : _ports.count();
}

int ConnectItemModel::columnCount(const QModelIndex &parent) const
{
	Q_UNUSED(parent);
	return COUNT_SECTION;
}
